using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.XPath;
using MagnoliaTableAdapters;

public partial class PackageList : System.Web.UI.Page
{

    static ArrayList globalResults = new ArrayList();
    static ArrayList globalSelected = new ArrayList();
    static int globalSelected_SI = -1;
    static int globalResults_SI = -1;

    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Title = ConfigurationManager.AppSettings["PageTitle"] + " - Package List";
        ListBox_Selected.Attributes.Add("onchange", "selectedIndexChange();");
        Label_PackageAlerts.Style.Add("display", "none");
        Label_PackageSearchAlerts.Style.Add("display", "none");

        // hide new button for user access
        Btn_New.Style.Add("display", "none");

        // get user access permissions
        DataTable UserAccessDT = (DataTable)Session["UserAccess"];
        foreach (DataRow dr in UserAccessDT.Rows)
        {
            // new user
            if (Convert.ToString(dr.ItemArray[0]) == "402")
            {
                Btn_New.Style.Add("display", "block");
            }
        }

        Btn_Edit.Attributes.Add("disabled", "disabled");
        Btn_Remove.Attributes.Add("disabled", "disabled");

        PreserveListItems();

        if (ListBox_Selected.Items.Count > 1)
        {
            Btn_EditAll.Enabled = true;
        }
        else
        {
            Btn_EditAll.Enabled = false;
        }

    }
    protected void Btn_Search_Click(object sender, EventArgs e)
    {
        DDList_Sort.SelectedIndex = 0;
        ListBox_Results.Items.Clear();
        globalResults.Clear();

        // query to get a list of items
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SuperSignConnectionString"].ConnectionString);
        try
        {
            conn.Open();

            String sProc = "sproc_WEB_GetListPackage";

            SqlCommand cmd = new SqlCommand(sProc, conn);
            cmd.CommandType = CommandType.StoredProcedure;

            // set paramter
            DbParameter param = cmd.CreateParameter();
            param.ParameterName = "@XML";
            param.Value = Session["ListSearchString"];
            param.DbType = DbType.Xml;
            cmd.Parameters.Add(param);

            param = cmd.CreateParameter();
            param.ParameterName = "@IncludeDisabled";
            param.Value = Convert.ToBoolean(Session["ListSearchIncludeDisabled"]);
            param.DbType = DbType.Boolean;
            cmd.Parameters.Add(param);

            // execute the stored procedure and return the results
            XmlReader xReader = cmd.ExecuteXmlReader();
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(xReader);
            xReader.Close();

            XmlNodeList nodes = xDoc.SelectNodes("//PACKAGE");
            globalResults.Clear();
            if (nodes.Count == 0)
            {
                Label_PackageSearchAlerts.Text = "No results were found for the given search criteria.";
                Label_PackageSearchAlerts.Style["color"] = "Green";
                Label_PackageSearchAlerts.Style["font-weight"] = "bold";
                Label_PackageSearchAlerts.Style["display"] = "block";
                return;
            }
            foreach (XmlNode xNode in nodes)
            {
                ListItem item = new ListItem();
                item.Text = Server.HtmlDecode(Convert.ToString(xNode.Attributes["Name"].InnerXml));
                item.Value = Convert.ToString(xNode.Attributes["ID"].InnerXml);
                String ThisEnabled = Convert.ToString(xNode.Attributes["ThisEnabled"].InnerXml);
                if (ThisEnabled == "0")
                    item.Attributes.Add("class", "disabledOption");
                try
                {
                    if ((xNode.HasChildNodes) && (xNode.FirstChild.Attributes.Count > 0))
                    {
                        item.Attributes.Add("label", Convert.ToString(xNode.FirstChild.Attributes["CreatedOn"].InnerXml));
                    }
                    else
                    {
                        item.Attributes.Add("label", "");
                    }
                }
                catch (Exception exception)
                {
                    String err = exception.Message;
                }

                ListBox_Results.Items.Add(item);
                globalResults.Add(item);
            }
        }
        catch (Exception exception)
        {
            String err = exception.Message;
        }
        finally
        {
            conn.Close();
        }
    }

    protected void Btn_Add_Click(object sender, EventArgs e)
    {
        if (ListBox_Selected.Items.Count < 3)
        {
            bool inList = false;
            foreach (ListItem item in ListBox_Selected.Items)
            {
                if (ListBox_Results.SelectedItem.Value == item.Value)
                {
                    inList = true;
                    break;
                }
            }
            if (!inList)
            {
                ListItem selectedItem = new ListItem();
                selectedItem.Text = ListBox_Results.SelectedItem.Text;
                selectedItem.Value = ListBox_Results.SelectedItem.Value;
                // get matching item in global array
                int index = 0;
                for (int i = 0; i < globalResults.Count; i++)
                {
                    ListItem tmpItem = ((ListItem)globalResults[i]);
                    if (tmpItem.Value == selectedItem.Value)
                    {
                        index = i;
                        break;
                    }
                }
                ListItem selectedGlobal = ((ListItem)globalResults[index]);
                if (selectedGlobal.Attributes["class"] != null)
                {
                    if (selectedGlobal.Attributes["class"].Contains("disabledOption"))
                    {
                        selectedItem.Attributes.Add("class", "disabledOption");
                    }
                }
                if (selectedGlobal.Attributes["label"] != null)
                {
                    if (selectedGlobal.Attributes["label"].Length > 0)
                    {
                        selectedItem.Attributes.Add("label", selectedGlobal.Attributes["label"]);
                    }
                }

                ListBox_Selected.Items.Add(selectedItem);
                globalSelected.Add(selectedItem);
                ListBox_Results.SelectedIndex = -1;
            }
        }
        ListBox_Selected.SelectedIndex = -1;
        if (ListBox_Selected.Items.Count > 1)
        {
            Btn_EditAll.Enabled = true;
        }
        else
        {
            Btn_EditAll.Enabled = false;
        }

        //PreserveListItems();
    }
    protected void Btn_Remove_Click(object sender, EventArgs e)
    {
        // Find and remove from global array as well
        for (int i = 0; i < globalSelected.Count; i++)
        {
            ListItem tmpItem = ((ListItem)globalSelected[i]);
            if (tmpItem.Value == ListBox_Selected.SelectedItem.Value)
            {
                globalSelected.RemoveAt(i);
            }
        }
        ListBox_Selected.Items.Remove(ListBox_Selected.SelectedItem);
        NameLabel.Text = "";
        ListBox_Selected.SelectedIndex = -1;
        Btn_Remove.Attributes.Add("disabled", "disabled");
        if (ListBox_Selected.Items.Count > 1)
        {
            Btn_EditAll.Enabled = true;
        }
        else
        {
            Btn_EditAll.Enabled = false;
        }
        //PreserveListItems();
    }
    protected void Btn_EditAll_Click(object sender, EventArgs e)
    {
        Hidden_BtnChoice.Value = "EditAll";
        //globalSelected.Clear();
    }
    protected void Btn_Edit_Click(object sender, EventArgs e)
    {
        Hidden_BtnChoice.Value = "Edit";
        //globalSelected.Clear();
    }
    protected void Btn_New_Click(object sender, EventArgs e)
    {
        Hidden_BtnChoice.Value = "New";
        //globalSelected.Clear();
    }

    private void ListBox_Results_DoubleClick(object sender, System.EventArgs e)
    {
        if (ListBox_Selected.Items.Count < 3)
        {
            bool inList = false;
            foreach (ListItem item in ListBox_Selected.Items)
            {
                if (ListBox_Results.SelectedItem.Value == item.Value)
                {
                    inList = true;
                    break;
                }
            }
            if (!inList)
            {
                ListBox_Selected.Items.Add(ListBox_Results.SelectedItem);
                ListBox_Results.SelectedIndex = -1;
            }
        }
    }
    protected void DDList_Sort_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (DDList_Sort.SelectedValue == "0")
        {
            //PreserveListItems();
        }
        if (DDList_Sort.SelectedValue == "1")
        {
            globalResults.Sort(new SortListByTextAsc());
            ListBox_Results.Items.Clear();
            for (int i = 0; i < globalResults.Count; i++)
            {
                ListBox_Results.Items.Add((ListItem)globalResults[i]);
            }
        }
        else if (DDList_Sort.SelectedValue == "2")
        {
            globalResults.Sort(new SortListByIDDesc());
            ListBox_Results.Items.Clear();
            for (int i = 0; i < globalResults.Count; i++)
            {
                ListBox_Results.Items.Add((ListItem)globalResults[i]);
            }
        }
    }
    protected void PreserveListItems()
    {
        globalResults_SI = ListBox_Results.SelectedIndex;
        ListBox_Results.Items.Clear();
        for (int i = 0; i < globalResults.Count; i++)
        {
            ListBox_Results.Items.Add((ListItem)globalResults[i]);
        }
        ListBox_Results.SelectedIndex = globalResults_SI;

        globalSelected_SI = ListBox_Selected.SelectedIndex;
        ListBox_Selected.Items.Clear();
        for (int i = 0; i < globalSelected.Count; i++)
        {
            ListBox_Selected.Items.Add((ListItem)globalSelected[i]);
        }
        ListBox_Selected.SelectedIndex = globalSelected_SI;
    }
    protected void ListBox_Results_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ListBox_Results.SelectedIndex != -1)
        {
            Btn_Add.Enabled = true;
        }
        else
        {
            Btn_Add.Enabled = false;
        }
    }
}
